#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <desktopitem.h>>
#include <chesspiece.h>
#include <chessdata.h>
#include <QHash>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    scene=new GameScene(ui->centralwidget);
    scene->setBackgroundBrush(Qt::gray);
    //棋盘初始化
    view=new QGraphicsView(scene,ui->centralwidget);
    ui->centralwidget->resize(this->width(),this->height());
    int w=ui->centralwidget->width();
    int h=ui->centralwidget->height();
    qDebug()<<w<<"dd"<<h;
    scene->setSceneRect(0,0,w-105,h-105);
    view->setGeometry(0,0,w-100,h-100);

    qDebug()<<view->width()<<"dd"<<view->height()<<"sw="<<  scene->width()<<"sh="<<scene->height();
    DesktopItem* deskItem=new DesktopItem(view->width(),view->height());
    deskItem->initDesktop();
    deskItem->setPos(0,0);
    scene->addItem(deskItem);
    scene->saveDesktopItem(deskItem);




    //生成棋盘数据
    //全局棋牌数据
    scene->initGameScene();
    const ChessData* chd=scene->getChessData();
    //连接信号和槽
    QObject::connect(chd->sendBus,&SendBus::sendSideChange,deskItem,&DesktopItem::sideChange);
    QObject::connect(chd->sendBus,&SendBus::sendGameStartToPainter,deskItem,&DesktopItem::setGameStart);
    QObject::connect(chd->sendBus,&SendBus::sendViewUpdate,this,&MainWindow::updateView);

    emit chd->sendBus->sendSideChange(chd->sideStep,chd->sideBelow);

    scene->saveSxSy(deskItem->getSx(),deskItem->getSy(),deskItem->getR(),deskItem->getD());

    //const ChessData* chd=scene->getChessData();


    //scene->printBoardInfo();


    //view->show();





}

void MainWindow::updateView()
{
    const ChessData* chd=scene->getChessData();

    for(int i=0;i<9;i++){
        for(int k=0;k<10;k++){
            PieceData* ped=chd->boardTable[i][k];
            if(ped==nullptr){
                scene->saveChessPiece(nullptr,i,k);
                continue;
            }
            //qDebug()<<"init before::"<<"i_k="<<i<<"_"<<k<<":"<<ped->textName<<"||"<<ped->cx<<"_"<<ped->cy;

            ChessPiece* piece=new ChessPiece(chd->sx,chd->sy,chd->r,ped->id);
            piece->initChessPiece(ped->textName,ped->cx,ped->cy,ped->type,ped->kind);
            scene->addItem(piece);
            scene->saveChessPiece(piece,i,k);
            //qDebug()<<"init after::"<<"i_k="<<i<<"_"<<k<<":"<<piece->getTextName()<<"||"<<piece->getCx()<<"_"<<piece->getCy();
        }
    }

    view->show();
}



MainWindow::~MainWindow()
{
    delete ui;
    delete scene;
    delete view;

}

 GameScene &MainWindow::getGameScene()
{
    return *this->scene;
}

 QGraphicsView &MainWindow::getQGraphicsView()
{
     return *this->view;
 }


